package com.promise.jokerdream.work.faction

import com.promise.jokerdream.manager.ExecutionHistoryManager
import com.promise.jokerdream.repository.GameApi
import com.promise.jokerdream.repository.foldWithApiException
import com.promise.jokerdream.utils.AppContext
import com.promise.jokerdream.work.BaseWork
import com.promise.jokerdream.work.WorkResult

// 粮草工作
class FactionForageWork(override val uin: String): BaseWork(uin) {

    override val name: String
        get() = "粮草"

    override val priority: Int
        get() = 1

    private val gameApi = GameApi.getInstance()
    private val historyManager by lazy { ExecutionHistoryManager.getInstance(AppContext.get()) }

    override suspend fun executeWork(): WorkResult {
        try {
            // 查询粮草信息
            val forageResult = gameApi.queryForageWar()
            return forageResult.foldWithApiException(
                onSuccess = { forageResponse ->
                    if (forageResponse.gift == 1) {
                        val claimResult = gameApi.claimForageWar()
                        claimResult.foldWithApiException(
                            onSuccess = { claimResponse ->
                                historyManager.addHistory(name, claimResponse.getDescription())
                                WorkResult.Success
                            },
                            onFailure = { code, msg ->
                                historyManager.addHistory(name, msg, code)
                                WorkResult.Failure(Exception(msg), msg)
                            }
                        )
                    } else {
                        WorkResult.Success
                    }
                },
                onFailure = { code, msg ->
                    historyManager.addHistory(name, msg, code)
                    WorkResult.Failure(Exception(msg), msg)
                }
            )
        } catch (e: Exception) {
            historyManager.addHistory(name, e.message)
            return WorkResult.Failure(e, e.message)
        }
    }
}